import { createApp } from 'vue'
import ElementPlus, { ElMessage, ElMessageBox } from 'element-plus'
import 'element-plus/dist/index.css'
import axios from 'axios'
import App from './App.vue'
import router from './router'
import store from './store'
import useTool from '../public/static/js/tool'

// 创建axios实例
const axiosInstance = axios.create({
  baseURL: '/api',
  timeout: 10000 // 请求超时时间
})

// 请求拦截器
/**
 * axios拦截器
 */
axiosInstance.interceptors.request.use((config) => {
  const newConfig = { ...config }
  const { getLoginAdmin } = useTool()
  newConfig.headers.token = getLoginAdmin()
  newConfig.headers.type = 'hongyy'
  return newConfig
}, (error) => Promise.reject(error))

// 响应拦截器
// 修改为 async 函数
axiosInstance.interceptors.response.use(
  (response) => {
    if (response.data.code === -12) {
      try {
        ElMessageBox.alert(response.data.msg, '消息提示', {
          confirmButtonText: '重新登录!',
          showClose: false
        })
        // 触发跳转逻辑
        router.push('/login')
        return null
      } catch (error) {
        // 你可以处理弹窗关闭后的其他逻辑
        return Promise.reject(error)
      }
    }
    return response
  },
  (error) => Promise.reject(error)
)

const app = createApp(App)
// 将axios实例挂载到Vue原型上，这样在Vue组件中就可以通过this.$axios访问
app.config.globalProperties.$ajax = axiosInstance
app.use(ElementPlus)
app.config.globalProperties.$message = function (msg) {
  return ElMessage({
    message: msg,
    duration: 1000
  })
}
// 分别对success、warning和error等样式进行设置
app.config.globalProperties.$message.success = function (msg) {
  return ElMessage.success({
    message: msg,
    duration: 1000
  })
}
app.config.globalProperties.$message.warning = function (msg) {
  return ElMessage.warning({
    message: msg,
    duration: 1000
  })
}
app.config.globalProperties.$message.error = function (msg) {
  return ElMessage.error({
    message: msg,
    duration: 1000
  })
}
app.use(store).use(router)

// 路由登录拦截 - 移动到router挂载之后
router.beforeEach((to, from, next) => {
  const { getLoginAdmin, isEmpty } = useTool()
  const token = getLoginAdmin()

  // 检查目标路由是否需要登录
  const requiresAuth = to.matched.some((route) => route.meta.requiresAuth)

  if (requiresAuth) {
    // 如果没有 token，跳转到登录页
    if (isEmpty(token)) {
      next('/login')
    } else {
      next() // 如果有 token，继续访问目标页面
    }
  } else {
    next() // 如果页面不需要登录，直接放行
  }
})

app.mount('#app')
